import {BaseResponse} from "../../core/BaseResponse";
import crypto from 'crypto';

module.exports = class extends saas.Service {
    async checkLogin(userName, passWord) {
        userName = userName.trim();
        passWord = passWord.trim();
        const encryptedPassWord = saas.md5(passWord + userName.toUpperCase() + saas.config.md5Salt);

        const adminInfo = await this.model('admin').checkLogin(userName, encryptedPassWord);
        if (saas.isEmpty(adminInfo)) {
            return new BaseResponse(false, null, '用户名密码错误');
        }
        if (adminInfo.status != 0) {
            return new BaseResponse(false, null, '账户被禁用');
        }
        adminInfo.last_login_time = Date.now();
        await this.model('admin').update(adminInfo.id, adminInfo);
        // 生成登录token
        adminInfo.token = await this.createToken(adminInfo, saas.config.tokenExpireTime);
        return new BaseResponse(true, adminInfo);
    }

    private async createToken(adminInfo: any, expires: number) {
        // 1.先生成token
        const token = crypto.createHash('sha256').update(JSON.stringify(adminInfo)).digest('hex');
        // 2.用户信息存入缓存
        await saas.cache(`adminInfo_${token}`, adminInfo, expires);
        return token;
    }

    private async refreshToken(token, adminInfo) {
        await saas.cache(`adminInfo_${token}`, adminInfo, saas.config.tokenExpireTime);
    }

    async getAdminInfoByToken(token: string) {
        const adminInfo = await saas.cache(`adminInfo_${token}`);
        if (adminInfo) {
            await this.refreshToken(token, adminInfo);
        }
        return adminInfo;
    }
}